<template>
  <view class="index-container">
    <!-- 搜索栏和位置选择 -->
    <!-- <view class="header">
      <view class="location" @tap="chooseLocation">
        <text class="location-icon">📍</text>
        <text class="location-text">{{ currentLocation.address || '定位中...' }}</text>
        <text class="location-arrow">▼</text>
      </view>
      <view class="search-bar">
        <view class="search-box" @click="goToSearch">
          <text class="search-icon">🔍</text>
          <text class="placeholder">搜索医生、疾病、药品</text>
        </view>
      </view>
    </view> -->
    
    <!-- 轮播图 -->
    <swiper class="banner" circular autoplay :interval="3000" :duration="500" @change="handleSwiperChange">
      <swiper-item v-for="(item, index) in banners" :key="index" @click="handleBannerClick(item)">
        <image :src="item.image_url" mode="aspectFill" class="banner-image"></image>
      </swiper-item>
      <view class="swiper-dots">
        <view 
          v-for="(item, index) in banners" 
          :key="index" 
          class="dot"
          :class="{ active: currentSwiper === index }"
        ></view>
      </view>
    </swiper>
    
    <!-- 快捷功能 -->
    <view class="quick-actions">
      <view class="action-item" v-for="(item, index) in quickActions" :key="index" @click="handleQuickAction(item)">
        <text class="action-icon">{{ item.icon }}</text>
        <text class="action-name">{{ item.name }}</text>
      </view>
    </view>

    <!-- 体检服务 -->
    <view class="section" v-if="checkupPackages.length > 0">
      <view class="section-header">
        <text class="title">体检服务</text>
        <text class="more" @click="goToCheckup">更多</text>
      </view>
      <scroll-view class="package-list" scroll-x>
        <view class="package-item" v-for="(pkg, index) in checkupPackages" :key="index" @click="goToPackageDetail(pkg)">
          <image :src="pkg.image" mode="aspectFill" class="package-image" @error="handlePackageImageError($event, index)"></image>
          <view class="package-info">
            <text class="package-name">{{ pkg.name }}</text>
            <text class="package-desc">{{ pkg.description }}</text>
            <view class="package-price">
              <text class="price">¥{{ pkg.price }}</text>
              <text class="original-price" v-if="pkg.originalPrice">¥{{ pkg.originalPrice }}</text>
            </view>
          </view>
        </view>
      </scroll-view>
    </view>

    <!-- 医院列表 -->
    <view class="section" v-if="nearbyHospitals.length > 0">
      <view class="section-header">
        <text class="title">医院列表</text>
        <text class="more" @click="goToHospitalList">更多</text>
      </view>
      <view class="hospital-list">
        <view class="hospital-item" v-for="(hospital, index) in nearbyHospitals" :key="index" @click="goToHospitalDetail(hospital)">
          <image :src="hospital.image" mode="aspectFill" class="hospital-image" @error="handleImageError($event, index)"></image>
          <view class="hospital-info">
            <text class="hospital-name">{{ hospital.name }}</text>
            <view class="distance-info">
              <text class="hospital-address">{{ hospital.address }}</text>
            </view>
            <view class="hospital-tags">
              <text class="tag" v-for="(tag, tagIndex) in hospital.tags" :key="tagIndex">{{ tag }}</text>
            </view>
          </view>
          <view class="hospital-actions">
            <button class="map-btn" @tap.stop="showHospitalLocation(hospital)">查看地图</button>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { slideshowApi } from '@/api/slideshow'
import { hospitalApi } from '@/api/hospital'
import { setmealApi } from '@/api/setmeal'
import { getHospitalList } from '@/api/hospital'

export default {
  data() {
    return {
      currentSwiper: 0,
      banners: [],
      quickActions: [
        { name: '在线问诊', icon: '👨‍⚕️', path: '/pages/consultation/consultation' },
        // { name: '体检预约', icon: '🏥', path: '/pages/checkup/checkup' },
        { name: '在线买药', icon: '💊', path: '/pages/pharmacy/pharmacy' },
        // { name: '健康档案', icon: '📋', path: '/pages/medical-records/medical-records' },
        { name: '疫苗接种', icon: '💉', path: '/pages/vaccination/vaccination' },
		{ name: '智能客服', icon: '🤖', path: '/pages/customer-service/customer-service' }
      ],
      checkupPackages: [],
      nearbyHospitals: [],
      currentLocation: {
        latitude: 0,
        longitude: 0,
        address: '定位中...'
      }
    }
  },

  onLoad() {
    // 获取本地存储的位置信息
    const savedLocation = uni.getStorageSync('currentLocation')
    if (savedLocation) {
      this.currentLocation = savedLocation
    }
    
    this.loadSlideshow()
    this.loadCheckupPackages()
    this.loadHospitals()
  },

  methods: {
    // 加载轮播图数据
    async loadSlideshow() {
      try {
        const res = await slideshowApi.getSlideshow()
        console.log('轮播图数据:', res) // 添加日志
        if (res.code === 200 && res.data) {
          if (Array.isArray(res.data)) {
            // 确保数据是数组
            this.banners = res.data.map(item => ({
              image_url: item.imageUrl || item.image_url,
              link_url: item.linkUrl || item.link_url,
              title: item.title,
              sort_order: item.sortOrder || item.sort_order || 0
            })).sort((a, b) => a.sort_order - b.sort_order)
          }
        }
        // 如果没有数据，使用默认图片
        if (!this.banners || this.banners.length === 0) {
          this.banners = [
            {
              image_url: '/static/banner/banner1.jpg',
              link_url: '/pages/health/health',
              title: '健康服务'
            },
            {
              image_url: '/static/banner/banner2.jpg',
              link_url: '/pages/community/community',
              title: '社区服务'
            }
          ]
        }
      } catch (error) {
        console.error('加载轮播图失败:', error)
        // 使用默认数据
        this.banners = [
          {
            image_url: '/static/banner/banner1.jpg',
            link_url: '/pages/health/health',
            title: '健康服务'
          },
          {
            image_url: '/static/banner/banner2.jpg',
            link_url: '/pages/community/community',
            title: '社区服务'
          }
        ]
      }
    },

    handleSwiperChange(e) {
      this.currentSwiper = e.detail.current
    },

    handleBannerClick(item) {
      if (item.link_url) {
        uni.navigateTo({
          url: item.link_url,
          fail: (err) => {
            console.error('页面跳转失败:', err)
            uni.showToast({
              title: '页面跳转失败',
              icon: 'none'
            })
          }
        })
      }
    },

    handleQuickAction(item) {
      if (item.path) {
        uni.navigateTo({
          url: item.path
        })
      }
    },

    goToSearch() {
      uni.navigateTo({
        url: '/pages/search/search'
      })
    },

    async loadCheckupPackages() {
      try {
        const res = await setmealApi.getAllSetMeal()
        console.log('体检套餐数据:', res) // 添加日志
        if (res.code === 200 && res.data) {
          // 转换后端数据格式为前端所需格式
          this.checkupPackages = res.data.map(pkg => ({
            id: pkg.id,
            name: pkg.name,
            description: pkg.remark || `适合${pkg.age}岁${pkg.sex === '0' ? '男女' : (pkg.sex === '1' ? '男' : '女')}性`,
            price: pkg.price,
            originalPrice: Math.floor(pkg.price * 1.2), // 原价设置为当前价格的1.2倍
            image: pkg.img || '/static/images/checkup-default.jpg' // 直接使用返回的完整图片URL
          }))
        }
      } catch (error) {
        console.error('加载体检套餐失败:', error)
        uni.showToast({
          title: '加载体检套餐失败',
          icon: 'none'
        })
        // 使用默认数据
        this.checkupPackages = [
          {
            id: 1,
            name: '标准体检套餐',
            description: '适合25-45岁人群的基础体检套餐',
            price: 599,
            originalPrice: 899,
            image: '/static/images/checkup1.jpg'
          },
          {
            id: 2,
            name: '关爱父母套餐',
            description: '专为中老年人设计的体检套餐',
            price: 999,
            originalPrice: 1299,
            image: '/static/images/checkup2.jpg'
          }
        ]
      }
    },

    // 获取当前位置
    getLocation() {
      uni.getLocation({
        type: 'gcj02',
        success: (res) => {
          this.currentLocation.latitude = res.latitude
          this.currentLocation.longitude = res.longitude
          this.getLocationAddress(res.latitude, res.longitude)
        },
        fail: (err) => {
          console.error('获取位置失败:', err)
          uni.showToast({
            title: '获取位置信息失败，请检查权限设置',
            icon: 'none'
          })
        }
      })
    },

    // 获取位置地址信息
    getLocationAddress(latitude, longitude) {
      uni.request({
        url: `https://apis.map.qq.com/ws/geocoder/v1/?location=${latitude},${longitude}&key=YOUR_KEY`,
        success: (res) => {
          if (res.data && res.data.result) {
            this.currentLocation.address = res.data.result.address
          }
        }
      })
    },

    // 加载医院列表
    async loadHospitals() {
      console.log('开始获取医院列表');
      
      uni.request({
        url: 'http://localhost:8090/hospital/findHospitals',
        method: 'GET',
        success: (res) => {
          console.log('获取医院列表成功:', res);
          if (res.statusCode === 200 && res.data.code === 200) {
            const hospitals = res.data.data;
            // 获取所有医院的地址信息
            const addressIds = hospitals.map(hospital => hospital.addressId);
            this.getAddressesByIds(addressIds, hospitals);
          } else {
            uni.showToast({
              title: res.data.msg || '获取医院列表失败',
              icon: 'none'
            });
          }
        },
        fail: (err) => {
          console.error('获取医院列表请求失败:', err);
          uni.showToast({
            title: '网络请求失败',
            icon: 'none'
          });
        }
      });
    },

    // 根据ID批量获取地址信息
    getAddressesByIds(addressIds, hospitals) {
      console.log('开始获取地址信息, addressIds:', addressIds);
      
      // 使用Promise.all并发获取所有地址信息
      const addressPromises = addressIds.map(id => {
        return new Promise((resolve, reject) => {
          uni.request({
            url: `http://localhost:8090/address/${id}`,
            method: 'GET',
            success: (res) => {
              if (res.statusCode === 200 && res.data.code === 200) {
                resolve(res.data.data);
              } else {
                resolve(null); // 如果获取失败返回null
              }
            },
            fail: (err) => {
              console.error(`获取地址ID ${id} 失败:`, err);
              resolve(null);
            }
          });
        });
      });
      
      Promise.all(addressPromises).then(addresses => {
        // 将地址信息关联到医院数据中
        const hospitalsWithAddress = hospitals.map(hospital => {
          const address = addresses.find(addr => addr && addr.id === hospital.addressId);
          return {
            id: hospital.id,
            name: hospital.name,
            address: address ? `${address.province}${address.city}${address.district}${address.detailedAddress}` : '地址未知',
            tags: [ '医院',`${hospital.doctorsNum || 0}名医生`],
            image: hospital.imgurl || '/static/images/hospital-default.jpg',
            location: {
              latitude: Number(hospital.latitude),
              longitude: Number(hospital.longitude)
            }
          };
        });
        
        // 只取前两个医院
        this.nearbyHospitals = hospitalsWithAddress.slice(0, 2);
        console.log('设置后的医院列表:', this.nearbyHospitals);
      }).catch(err => {
        console.error('获取地址信息失败:', err);
        uni.showToast({
          title: '获取地址信息失败',
          icon: 'none'
        });
      });
    },

    goToCheckup() {
      uni.navigateTo({
        url: '/pages/checkup/package-list'
      })
    },

    goToPackageDetail(pkg) {
      uni.navigateTo({
        url: `/pages/checkup/detail?id=${pkg.id}`
      })
    },

    goToHospitalMap() {
      uni.navigateTo({
        url: '/pages/hospital/map'
      })
    },
    goToHospitalList() {
      uni.navigateTo({
        url: `/pages/hospital/list`,
      })
    },

    goToHospitalDetail(hospital) {
      if (!hospital || !hospital.id) {
        uni.showToast({
          title: '医院信息不完整',
          icon: 'none'
        })
        return
      }
      
      uni.navigateTo({
        url: `/pages/hospital/detail?id=${hospital.id}`,
        success: () => {
          console.log('跳转医院详情页成功')
        },
        fail: (err) => {
          console.error('跳转医院详情页失败:', err)
          uni.showToast({
            title: '跳转失败，请稍后重试',
            icon: 'none'
          })
        }
      })
    },

    // 选择位置
    chooseLocation() {
      uni.chooseLocation({
        success: (res) => {
          this.currentLocation = {
            latitude: res.latitude,
            longitude: res.longitude,
            address: res.address
          }
          // 保存当前位置到本地存储
          uni.setStorageSync('currentLocation', this.currentLocation)
          // 重新加载医院列表
          this.loadHospitals()
        },
        fail: (err) => {
          console.error('选择位置失败:', err)
          uni.showToast({
            title: '选择位置失败',
            icon: 'none'
          })
        }
      })
    },

    showHospitalLocation(hospital) {
      // 在控制台输出医院信息
      console.log('医院详细信息:', {
        医院名称: hospital.name,
        医院地址: hospital.address,
        经度: hospital.location.longitude,
        纬度: hospital.location.latitude,
        完整信息: hospital
      })

      if (!hospital.location || !hospital.location.latitude || !hospital.location.longitude) {
        uni.showToast({
          title: '医院位置信息不完整',
          icon: 'none'
        })
        return
      }

      uni.openLocation({
        latitude: hospital.location.latitude,
        longitude: hospital.location.longitude,
        name: hospital.name,
        address: hospital.address,
        success: () => {
          console.log('打开地图成功')
        },
        fail: (err) => {
          console.error('打开地图失败:', err)
          uni.showToast({
            title: '打开地图失败',
            icon: 'none'
          })
        }
      })
    },

    // 处理图片加载错误
    handleImageError(e, index) {
      // 当图片加载失败时，使用默认图片
      this.nearbyHospitals[index].image = '/static/images/hospital-default.jpg'
    },

    // 处理套餐图片加载错误
    handlePackageImageError(e, index) {
      console.error('套餐图片加载失败:', this.checkupPackages[index].image)
      this.checkupPackages[index].image = '/static/images/checkup-default.jpg'
    }
  }
}
</script>

<style lang="scss">
.index-container {
  min-height: 100vh;
  background: #f5f5f5;
  padding-bottom: 20rpx;

  .header {
    display: flex;
    align-items: center;
    padding: 20rpx 30rpx;
    background: #fff;
    
    .location {
      display: flex;
      align-items: center;
      margin-right: 20rpx;
      
      .location-icon {
        font-size: 32rpx;
        margin-right: 10rpx;
      }
      
      .location-text {
        color: #333;
        font-size: 28rpx;
      }
      
      .location-arrow {
        font-size: 24rpx;
        color: #007AFF;
      }
    }
  }
  
  .search-bar {
    flex: 1;
    
    .search-box {
      display: flex;
      align-items: center;
      background: #f5f5f5;
      height: 72rpx;
      border-radius: 36rpx;
      padding: 0 30rpx;
      
      .search-icon {
        margin-right: 10rpx;
        font-size: 32rpx;
      }
      
      .placeholder {
        color: #999;
        font-size: 28rpx;
      }
    }
  }
  
  .banner {
    width: 100%;
    height: 300rpx;
    position: relative;
    margin: 20rpx 0;
    
    .banner-image {
      width: 100%;
      height: 100%;
      border-radius: 12rpx;
    }
    
    .swiper-dots {
      position: absolute;
      bottom: 20rpx;
      left: 50%;
      transform: translateX(-50%);
      display: flex;
      justify-content: center;
      align-items: center;
      
      .dot {
        width: 12rpx;
        height: 12rpx;
        background: rgba(255, 255, 255, 0.6);
        border-radius: 50%;
        margin: 0 8rpx;
        transition: all 0.3s;
        
        &.active {
          width: 24rpx;
          border-radius: 12rpx;
          background: #ffffff;
        }
      }
    }
  }
  
  .quick-actions {
    display: flex;
    justify-content: space-between;
    padding: 30rpx;
    background: #fff;
    
    .action-item {
      flex: 1;
      display: flex;
      flex-direction: column;
      align-items: center;
      margin-bottom: 20rpx;
      
      .action-icon {
        font-size: 48rpx;
        margin-bottom: 10rpx;
      }
      
      .action-name {
        font-size: 24rpx;
        color: #333;
      }
    }
  }

  .section {
    margin-top: 20rpx;
    background: #fff;
    padding: 30rpx;
    
    .section-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20rpx;
      
      .title {
        font-size: 32rpx;
        font-weight: bold;
        color: #333;
      }
      
      .more {
        font-size: 24rpx;
        color: #007AFF;
      }
    }
    
    .package-list {
      white-space: nowrap;
      
      .package-item {
        display: inline-block;
        width: 500rpx;
        margin-right: 20rpx;
        border-radius: 12rpx;
        overflow: hidden;
        background: #fff;
        box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.1);
        
        .package-image {
          width: 100%;
          height: 250rpx;
        }
        
        .package-info {
          padding: 20rpx;
          
          .package-name {
            font-size: 28rpx;
            color: #333;
            font-weight: bold;
          }
          
          .package-desc {
            font-size: 24rpx;
            color: #666;
            margin: 10rpx 0;
          }
          
          .package-price {
            display: flex;
            align-items: baseline;
            
            .price {
              font-size: 32rpx;
              color: #ff4d4f;
              font-weight: bold;
            }
            
            .original-price {
              font-size: 24rpx;
              color: #999;
              text-decoration: line-through;
              margin-left: 10rpx;
            }
          }
        }
      }
    }
    
    .hospital-list {
      .hospital-item {
        display: flex;
        padding: 20rpx 0;
        border-bottom: 1rpx solid #eee;
        
        &:last-child {
          border-bottom: none;
        }
        
        .hospital-image {
          width: 160rpx;
          height: 120rpx;
          border-radius: 8rpx;
          margin-right: 20rpx;
        }
        
        .hospital-info {
          flex: 1;
          
          .hospital-name {
            font-size: 28rpx;
            color: #333;
            font-weight: bold;
          }
          
          .distance-info {
            margin: 10rpx 0;
            
            .hospital-address {
              font-size: 24rpx;
              color: #666;
            }
          }
          
          .hospital-tags {
            display: flex;
            flex-wrap: wrap;
            
            .tag {
              font-size: 22rpx;
              color: #007AFF;
              background: rgba(0,122,255,0.1);
              padding: 4rpx 12rpx;
              border-radius: 4rpx;
              margin-right: 10rpx;
              margin-bottom: 10rpx;
            }
          }
        }
        
        .hospital-actions {
          display: flex;
          align-items: center;
          
          .map-btn {
            font-size: 24rpx;
            color: #007AFF;
            background: none;
            border: none;
            padding: 0;
            margin: 0;
          }
        }
      }
    }
  }
}
</style> 